#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

void Usage(std::string proc)
{
    std::cout << "\r\nUsage: " << proc << "serverip serverport\n"
              << std::endl;
}
//./udpclient serverip serverport 客户端必须知道服务端的Ip和端口号
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(server);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }
    string message;
    char buffer[1024];
    while (true)
    {
        cout << "Please Enter@";
        getline(cin, message);
        std::cout << message << endl;
        // 1.客户端发数据，2.给谁发
        sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&server, len);
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        // 客户端收到服务端处理后的数据,用temp结构体存储处理后返回的数据,
        // 这里不需要显示的写出接收哪里传来的报文
        // 因为上面首先向服务端发送了消息，返回的消息一定也是服务端的
        ssize_t s = recvfrom(sockfd, buffer, 1023, 0, (sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0; // 添加\0
            cout << buffer << endl;
        }
    }

    return 0;
}